<?php
/*
 * @Author: lokei
 * @Date: 2023-10-11 11:25:13
 * @LastEditors: lokei
 * @LastEditTime: 2023-10-11 11:51:58
 * @Description: 
 */
namespace App\Http\Controllers\Pay\Weixin;

use App\Common\Tools\ResultTool;
use App\Common\Tools\Sn;
use App\Http\Controllers\Controller;
use App\Models\Platform\Conf\ConfMiniappModel;
use App\Models\Ucenter\FansModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class TransferController extends Controller {
    public function batches(Request $request) {
        $fans = FansModel::where('uid', '=', $request->input('uid'))->where('platform', '=', 'miniapp')->first();
        if (!is_null($fans)) {
            $instance = Init::getInstance(0);

            $appid = '';
            if (config('app.proj_identity') != null && config('app.proj_identity') != '') {
                $endapp = Redis::get('proj:' . config('app.proj_identity') . ':miniapp');
                $endapp_info = json_decode($endapp);
                $appid = $endapp_info->appid;
            } else {
                $conf = ConfMiniappModel::first();
                $appid = $conf->appid;
            }
            
            $sn = Sn::build_order_no();
            $batch_name = '微信转账';

            $json_params = [
                'appid' => $appid,
                'out_batch_no' => $sn,
                'batch_name' => $batch_name,
                'batch_remark' => '微信转账',
                'total_amount' => intval($request->input('money') * 100),
                'total_num' => 1,
                'transfer_detail_list' => [
                    [
                        'out_detail_no' => Sn::build_order_no(),
                        'transfer_amount' => intval($request->input('money') * 100),
                        'transfer_remark' => '微信转账',
                        'openid' => $fans->openid
                    ]
                ]
            ];
            $resp = $instance
                ->v3->transfer->batches
                ->post(['json' => $json_params]);
            $jsapi_result = json_decode($resp->getBody()->getContents());

            if ($jsapi_result->batch_id != null && $jsapi_result->batch_id != '') {
                $res = ResultTool::success();
                $res['data']['batch_id'] = $jsapi_result->batch_id;
                return $res;
            } else {
                app('log')->info($jsapi_result);
                return ResultTool::fail();
            }
        }
    }
}